package com.mzj.saas.jobs.wallet.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mzj.saas.jobs.commons.DateUtils;
import com.mzj.saas.jobs.wallet.entity.Wallet;
import com.mzj.saas.jobs.wallet.entity.WalletBuffer;
import com.mzj.saas.jobs.wallet.repository.WalletBufferRepository;
import com.mzj.saas.jobs.wallet.repository.WalletRepository;

/**
 * 支付缓冲期操作
 */
@Service
public class WalletService {
    private static Logger log = LoggerFactory.getLogger(WalletService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WalletRepository walletRepository;
    @Autowired
    private WalletBufferRepository walletBufferRepository;
    
    public String work() throws Exception {
    	
    	try {
	    	String date = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_8);
	    	
	    	String sql  = "select id,order_number as orderNumber,wallet_id as walletId,total_amount as totalAmount from saas_wallet_buffer "
	    			+ "WHERE STATUS = 0 AND STR_TO_DATE(buffer_end_time,'%Y-%m-%d') = ?";
	    	
	    	List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,date);
	    	
	    	log.info("支付缓冲期操作 size={},date={}",list.size(),date);
	    	
	    	if(CollectionUtils.isEmpty(list)) {
	    		 return "SUCCESS";
	    	}
	    	Date updateDate = new Date();
	    	for(Map<String,Object> map : list) {
	    		Long id = Long.parseLong(map.get("id").toString());
	    		Long walletId = Long.parseLong(map.get("walletId").toString());
	    		String orderNumber  = map.get("orderNumber").toString();
	    		Integer totalAmount  = Integer.parseInt(map.get("totalAmount").toString());
	    		
	    		Wallet wallet =  walletRepository.findWalletById(walletId);
	    		
	    		if(wallet == null) {
	    			log.warn("支付缓冲期操作 wallet is null, id={},walletId={},orderNumber={}",id,walletId,orderNumber);
	    			continue;
	    		}
	    		//扣减缓冲期金额
	    		Integer bufferAmount = wallet.getBufferAmount() - totalAmount;
	    		//缓冲期金额增加到可提现金额
	    		Integer usableAmount =  wallet.getUsableAmount() + totalAmount;
	    		wallet.setBufferAmount(bufferAmount);
	    		wallet.setUsableAmount(usableAmount);
	    		wallet.setLastUpdateTime(updateDate);
	    		walletRepository.save(wallet);
	    		
	    		WalletBuffer walletBuffer =  walletBufferRepository.findWalletBufferById(id);
	    		walletBuffer.setStatus(1);
	    		walletBufferRepository.save(walletBuffer);
	    	}
    	}catch(Exception e) {
    		log.error(e.getMessage(),e);
    	}
    	
        return "SUCCESS";
    }
    
}
